package com.guxingke.gblog.controller.back;

import java.util.Date;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.guxingke.gblog.controller.BaseController;
import com.guxingke.gblog.dmo.Article;

@Controller
@RequestMapping("/manage/article")
public class ArticleManageController extends BaseController {

	@RequestMapping
	public ModelAndView list(HttpSession session) {
		ModelAndView mav = new ModelAndView();

		mav.addObject("articles", articleService.getArchive());
		mav.addObject("mainPage", "article/manage-list.jsp");

		mav.setViewName("manage");
		return mav;
	}

	@RequestMapping("/edit")
	public ModelAndView edit(
			@RequestParam(value = "articleId", required = true) Integer id) {
		ModelAndView mav = new ModelAndView();

		mav.addObject("article", articleService.getArticle(id));

		mav.addObject("mainPage", "article/manage-save.jsp");

		mav.setViewName("manage");
		return mav;
	}
	
	@RequestMapping("/show")
	public ModelAndView detail(
			@RequestParam(value = "articleId", required = true) Integer id) {
		ModelAndView mav = new ModelAndView();

		mav.addObject("article", articleService.getArticle(id));

		mav.addObject("mainPage", "article/manage-show.jsp");

		mav.setViewName("manage");
		return mav;
	}
	

	@RequestMapping("/new")
	public ModelAndView save() {
		ModelAndView mav = new ModelAndView();
		mav.addObject("mainPage", "article/manage-save.jsp");
		mav.setViewName("manage");
		return mav;
	}

	@RequestMapping("/delete")
	public String delete(
			@RequestParam(value = "articleId", required = true) Integer id) {
		
		articleService.deleteArticle(id);

		return "redirect:/manage/article.do";
	}
	
	@RequestMapping("/save")
	public String save(Article article) {
		//update
		if (article.getId()!=null) {
			articleService.updateArticle(article);
			return "redirect:/manage/article/show.do?articleId="+article.getId();
		}else {
			//new article
			article.setUserId(1);//TODO 暂时硬编码
			article.setPubDate(new Date());
			article.setClicks(0);
			article.setIsDraft(0);
			articleService.saveArticle(article);
		}
		return "redirect:/manage/article.do";
	}
}
